<template>
  <el-form ref="dynamicValidateForm" :model="form" label-width="100px">
    <el-form-item
      prop="email"
      label="邮箱"
      :rules="[
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
      ]"
    >
      <el-input v-model="form.email" />
    </el-form-item>
    <el-form-item
      v-for="(domain, index) in form.domains"
      :key="domain.key"
      :label="'域名' + index"
      :prop="'domains.' + index + '.value'"
      :rules="[
        { required: true, message: '请输入域名地址', trigger: 'blur' },
      ]"
    >
      <el-input v-model="domain.value" style="width: 50%; margin-right: 10px" /><el-button @click="removeDomain(domain)">删除</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
      <el-button @click="addDomain">新增域名</el-button>
      <el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      form: {
        email: '',
        domains: [{
          value: ''
        }]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        console.log(valid)
        if (valid) {
          // todo
          console.log(this.form)
        } else {
          return false
        }
      })
    },
    addDomain() {
      this.form.domains.push({
        value: '',
        key: Date.now()
      })
    },
    removeDomain(item) {
      const index = this.form.domains.indexOf(item)
      if (index !== -1) {
        this.form.domains.splice(index, 1)
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
